package com.dge.common.dialog

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.View
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.Permission
import com.dge.common.R
import com.dge.common.aop.Permissions
import com.dge.common.common.Constants
import com.dge.common.common.UserInfoMgr
import com.dge.common.databinding.DialogUpdateBinding
import com.dge.common.extentions.dp
import com.dge.common.interfaces.DownloadFileCallback
import com.dge.common.utils.FileUtil
import com.dge.common.utils.OkHttpUtils
import com.lxj.xpopup.core.CenterPopupView
import timber.log.Timber
import java.io.File

/**
 * 升级对话框
 */
class UpdateDialog(
    private val mContext: Context,
    private val mVersionName: String?,
    private val versionCode: Int,
    private val mFileSize: String?,
    private val mUpdateContext: String?,
    private val mDownloadUrl: String, //下载地址
    private val isForceUpdate: Boolean,
) : CenterPopupView(mContext), View.OnClickListener {
    companion object {
        var isUpdateRejected = false
    }

    private var _binding: DialogUpdateBinding? = null
    private val binding get() = _binding!!
    override fun getImplLayoutId(): Int {
        return R.layout.dialog_update
    }

    override fun onCreate() {
        _binding = DialogUpdateBinding.bind(popupImplView)
        UserInfoMgr.isLastUpdateCanceled = false
        UserInfoMgr.lastUpdateTimeMills = System.currentTimeMillis()
        binding.tvNewFeature.text = "新特性："
        binding.tvUpdateUpdate.setOnClickListener(this)
        binding.tvCancel.setOnClickListener(this)
        binding.tvUpdateName.text = mVersionName
        binding.tvUpdateSize.text = mFileSize
        binding.tvUpdateContent.text = mUpdateContext
        binding.tvUpdateContent.visibility = if (mUpdateContext == null) GONE else VISIBLE
        binding.tvCancel.visibility = if (isForceUpdate) GONE else VISIBLE
        binding.divider.visibility = if (isForceUpdate) GONE else VISIBLE
        if (isForceUpdate) {
            popupInfo?.isDismissOnBackPressed = false
            popupInfo?.isDismissOnTouchOutside = false
        }
        binding.pbUpdateProgress.max = 100
        binding.pbUpdateProgress.setProgressTextColor(context.resources.getColor(R.color.colorAccent))
        binding.pbUpdateProgress.reachedBarColor = context.resources.getColor(R.color.colorAccent)
        binding.scrollView.post {
            if (binding.scrollView.height > 250f.dp) {
                val params = binding.scrollView.layoutParams
                params.height = 250.dp
                binding.scrollView.layoutParams = params
            }
        }
    }

    override fun onClick(v: View) {
        val id = v.id
        if (id == R.id.tv_update_update) {
            UserInfoMgr.isLastUpdateCanceled = false
            requestPermission()
        } else if (id == R.id.tv_cancel) {
            UserInfoMgr.lastCanceledUpdateVersionCode = versionCode
            UserInfoMgr.isLastUpdateCanceled = true
            isUpdateRejected = true
            dismiss()
        }
    }

    fun downloadProgressChange(progress: Int) {
        binding.pbUpdateProgress.progress = progress
    }

    override fun onDismiss() {
        UserInfoMgr.saveUserInfo(Constants.firstIn)
    }

    /**
     * 请求权限，注：cache目录不需要申请存储权限
     */
    @Permissions(0, Permission.REQUEST_INSTALL_PACKAGES)
    private fun requestPermission() {
        popupInfo?.isDismissOnBackPressed = false
        popupInfo?.isDismissOnTouchOutside = false
        // 隐藏取消按钮
        binding.tvCancel.visibility = GONE
        binding.tvUpdateUpdate.setText(R.string.update_status_running)
        // 显示进度条
        binding.pbUpdateProgress.visibility = VISIBLE
        startDownLoad(
            mDownloadUrl, binding.tvUpdateName.text.toString() + ".apk"
        )
    }

    private fun isClickEnable(view: View, isEnable: Boolean) {
        if (isEnable) {
            view.isFocusable = true
            view.isClickable = true
            view.isEnabled = true
        } else {
            view.isFocusable = false
            view.isClickable = false
            view.isEnabled = false
        }
    }

    private fun startDownLoad(downloadUrl: String, fileName: String) {
        isClickEnable(binding.tvUpdateUpdate, false)
        val file = File(FileUtil.getCacheFilePath(fileName))
//        if (file.exists())
//            file.delete()
//        file.createNewFile()
        var lastProgress = 0
        OkHttpUtils.downLoadFile(downloadUrl, file, true, null, object : DownloadFileCallback {
            override fun onProgress(total: Long, current: Long) {
                val progress = (current.toDouble() / total * 100).toInt()
                if (progress != lastProgress) {
                    Timber.d("onProgress $total/$current, progress = $progress")
                    downloadProgressChange(progress)
                }
                lastProgress = progress
            }

            override fun successCallBack(file: File) {
                Timber.d("startDownLoad successCallBack file.path = ${file.absolutePath}")
                binding.tvUpdateUpdate.setText(R.string.update_status_successful)
                // 隐藏进度条
                isClickEnable(binding.tvUpdateUpdate, true)

                binding.pbUpdateProgress.visibility = GONE
                val intent = Intent()
                intent.action = Intent.ACTION_VIEW
                var uri = Uri.fromFile(file)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    try {
                        uri =
                            FileProvider.getUriForFile(mContext, Constants.fileProviderAuthority, file)
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    } catch (e: Exception) {
                        ToastUtils.showLong("文件读取失败，请在设置中尝试更新，或扫描二维码下载")
                        return
                    }
                }
                intent.setDataAndType(uri, "application/vnd.android.package-archive")
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                mContext.startActivity(intent)
            }

            override fun failedCallBack(msg: String) {
                isClickEnable(binding.tvUpdateUpdate, true)
                binding.pbUpdateProgress.visibility = GONE
                binding.tvUpdateUpdate.setText(R.string.update_download_fail)
                file.delete()
                if (!isForceUpdate) {
                    popupInfo?.isDismissOnBackPressed = true
                    popupInfo?.isDismissOnTouchOutside = true
                    binding.tvCancel.visibility = View.VISIBLE
                }
            }
        })
    }
}